from lib.sensors import max98357
from utils import common
import sys


text_list = []


def play(text):
    """播放文本"""
    common.print_gc_info()
    response = None
    try:
        response = wifi.UREQUEST_POST(
            "http://www.hanxiaoxin.cn:8080/tts",
            {
                "Text": text,
                "Codec": "wav",
                "EmotionCategory": "poetry",
                "VoiceType": 301000,
                "mime": "wav",
            },
            "raw",
        )

        while True:
            read_data = response.raw.read(1024 * 20)
            if not read_data:
                break

            # print(len(read_data))
            # common.print_gc_info()
            max98357.play_bytes(read_data)
    except Exception as e:
        sys.print_exception(e)
        response and response.close()


if __name__ == "__main__":
    import lib.net.wifi as wifi

    text_list.append("清明时节雨纷纷，路上行人欲断魂。")
    wifi.do_connect_wifi()
    max98357.init()
    for t in text_list:
        play(t)
